package com.recsmile.sgs.core.net.codec;

import com.recsmile.sgs.core.Command;
import com.recsmile.sgs.util.CommandManager;
import com.recsmile.sgs.util.SerializableUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by hanyuanliang on 16/8/24.
 */
public class ProtoBufEncoder extends MessageToByteEncoder<Command>{
    protected void encode(ChannelHandlerContext ctx, Command msg, ByteBuf out) throws Exception {
        byte[] array = SerializableUtil.toByteArray(msg);

        int len = array.length;

        ByteBuf buf = Unpooled.buffer(len + 6);
        buf.writeInt(len+2);
        buf.writeShort(CommandManager.findByClsName(msg.getClass().getName()));
        buf.writeBytes(array);
        out.writeBytes(buf);

        //System.out.println(Arrays.toString(buf.array()));
    }
}
